package com.lyq.interaction.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyq.interaction.model.Result;
import com.lyq.interaction.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            String token = (String) request.getSession().getAttribute("userToken");
            if (token == null) {
                return false;
            }
            Claims claims = JWTUtil.checkToken(token);
        }catch (Exception e) {
            setResponse(response);
            return false;
        }
        return true;
    }

    @SneakyThrows
    public void setResponse(HttpServletResponse response) {
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        String ret = objectMapper.writeValueAsString(Result.notAuthority());
        PrintWriter writer = response.getWriter();
        writer.print(ret);
        writer.flush();
    }
}
